import Vue from 'vue'
import VueRouter from 'vue-router'
//导入路由
import login from '@/views/user/login.vue'
import layout from '@/views/layout.vue'
import home from '@/views/home/home.vue'
import movie from '@/views/movie/movie.vue'
import qa from '@/views/qa/qa.vue'
import user from '@/views/user/user.vue'
import edit from '@/views/user/edit.vue'
import notfound from '@/views/notfound/notfound.vue'
import article from '@/views/home/article.vue'
import search from '@/views/home/search.vue'
import searchResult from '@/views/home/searchResult.vue'
import student from '@/views/user/student.vue'
Vue.use(VueRouter)

const routes = [{
    name: 'login',
    path: '/login',
    component: login
  },
  {
    name: 'edit',
    path: '/edit',
    component: edit,
  },
  {
    name: 'myarticle',
    path: '/article',
    component: article,
  },
  {
    name: 'search',
    path: '/search',
    component: search,
  },
  {
    name: 'searchResult',
    path: '/searchResult',
    component: searchResult,
  },
  {
    name: 'student',
    path: '/student',
    component: student,
  },
  // 二级路由
  {
    name: 'layout',
    path: '/',
    component: layout,
    children: [{
        name: 'home',
        path: '/home',
        component: home
      },

      {
        name: 'movie',
        path: '/movie',
        component: movie
      },
      {
        name: 'qa',
        path: '/qa',
        component: qa
      },
      {
        name: 'user',
        path: '/user',
        component: user,
        meta: {
          isLogin: true,
        }
      },

      { //重定向
        path: '/',
        redirect: '/home'
      }
    ]
  },
  {
    path: '/notfound',
    name: 'notfound',
    component: notfound
  },
  {
    path: '*', //乱敲的页面都走去404 一定放在最后面
    redirect: '/notfound'
  }

]

const router = new VueRouter({
  routes
})



// 导入 token 
import {
  getToken
} from '@/utils/token.js'

import {
  Toast
} from 'vant'

router.beforeEach((to, from, next) => {
  // to: 要跳转的路由 (要到哪里去)
  // console.log(to);

  // from: 从哪个路由跳转 (从哪里来)

  // next: 必须要的调用的 否则路由无法跳转
  // next() 没有传参 通过检查 允许跳转 to 页面
  // next('/path'): 传参数 没有通过检查 跳转到页面

  //   并不是所有页面都需要跳转，可以给一个判断
  if (to.meta.isLogin && !getToken()) {
    //   需要做登录判断
    if (getToken()) {
      // 有登陆 不拦截 无条件跳转
      next();
    } else {
      // 弹窗提示用户一下
      Toast.fail("请先登录")
      //   没有登录  拦截 跳转到登录页面
      next('/login')
    }
  } else {
    //   不需要做登录判断 无条件跳转
    next();
  }
})


export default router
